// CORS 中间件配置
export interface CorsOptions {
  origin?: string | string[] | boolean | ((origin: string) => boolean);
  methods?: string[];
  allowedHeaders?: string[];
  credentials?: boolean;
  maxAge?: number;
}

import config from '../config/env';

// 默认 CORS 配置
const defaultCorsOptions: CorsOptions = {
  origin: config.cors.origin,
  methods: config.cors.methods,
  allowedHeaders: config.cors.allowedHeaders,
  credentials: config.cors.credentials,
  maxAge: config.cors.maxAge
};

// 检查来源是否允许
function isOriginAllowed(origin: string, allowedOrigin: string | string[] | boolean | ((origin: string) => boolean)): boolean {
  if (typeof allowedOrigin === 'boolean') {
    return allowedOrigin;
  }
  
  if (typeof allowedOrigin === 'string') {
    return origin === allowedOrigin;
  }
  
  if (Array.isArray(allowedOrigin)) {
    return allowedOrigin.includes(origin);
  }
  
  if (typeof allowedOrigin === 'function') {
    return allowedOrigin(origin);
  }
  
  return false;
}

// 添加 CORS 头部到响应
export function addCorsHeaders(response: Response, origin: string, options: CorsOptions = defaultCorsOptions): Response {
  const headers = new Headers(response.headers);
  
  // 设置 Access-Control-Allow-Origin
  if (isOriginAllowed(origin, options.origin || true)) {
    headers.set('Access-Control-Allow-Origin', origin);
  } else {
    headers.set('Access-Control-Allow-Origin', '*');
  }
  
  // 设置 Access-Control-Allow-Methods
  if (options.methods) {
    headers.set('Access-Control-Allow-Methods', options.methods.join(', '));
  }
  
  // 设置 Access-Control-Allow-Headers
  if (options.allowedHeaders) {
    headers.set('Access-Control-Allow-Headers', options.allowedHeaders.join(', '));
  }
  
  // 设置 Access-Control-Allow-Credentials
  if (options.credentials) {
    headers.set('Access-Control-Allow-Credentials', 'true');
  }
  
  // 设置 Access-Control-Max-Age
  if (options.maxAge) {
    headers.set('Access-Control-Max-Age', options.maxAge.toString());
  }
  
  // 设置 Vary 头部
  headers.set('Vary', 'Origin');
  
  return new Response(response.body, {
    status: response.status,
    statusText: response.statusText,
    headers
  });
}

// 处理预检请求
export function handlePreflightRequest(req: Request, options: CorsOptions = defaultCorsOptions): Response {
  const origin = req.headers.get('Origin') || '';
  const method = req.headers.get('Access-Control-Request-Method') || '';
  const headers = req.headers.get('Access-Control-Request-Headers') || '';
  
  // 检查来源是否允许
  if (!isOriginAllowed(origin, options.origin || true)) {
    return new Response('CORS: Origin not allowed', { status: 403 });
  }
  
  // 检查方法是否允许
  if (options.methods && !options.methods.includes(method)) {
    return new Response('CORS: Method not allowed', { status: 405 });
  }
  
  // 创建预检响应
  const response = new Response(null, { status: 204 });
  return addCorsHeaders(response, origin, options);
}

// CORS 中间件包装器
export function withCors(handler: (req: Request) => Response | Promise<Response>, options: CorsOptions = defaultCorsOptions) {
  return async (req: Request): Promise<Response> => {
    const origin = req.headers.get('Origin') || '';
    
    // 处理预检请求
    if (req.method === 'OPTIONS') {
      return handlePreflightRequest(req, options);
    }
    
    // 执行原始处理器
    const response = await handler(req);
    
    // 添加 CORS 头部
    return addCorsHeaders(response, origin, options);
  };
}

// 批量处理路由的 CORS
export function withCorsForRoutes(routes: Record<string, any>, options: CorsOptions = defaultCorsOptions) {
  const corsRoutes: Record<string, any> = {};
  
  for (const [path, handler] of Object.entries(routes)) {
    if (typeof handler === 'function') {
      // 单个处理器
      corsRoutes[path] = withCors(handler, options);
    } else if (typeof handler === 'object' && handler !== null) {
      // 对象形式的处理器（如 { GET: handler, POST: handler }）
      const corsHandler: any = {};
      for (const [method, methodHandler] of Object.entries(handler)) {
        if (typeof methodHandler === 'function') {
          corsHandler[method] = withCors(methodHandler as (req: Request) => Response | Promise<Response>, options);
        } else {
          corsHandler[method] = methodHandler;
        }
      }
      corsRoutes[path] = corsHandler;
    } else {
      // 其他类型（如 Response 对象）
      corsRoutes[path] = handler;
    }
  }
  
  return corsRoutes;
}
